package com.tangerine.bd;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import com.tangerine.entidades.Favorito;

public class DbHandlerFavorito{	
	private static DbHandler bd; 
	private static final String TABLE_FAVORITO	= "FAVORITO";
	private static final String TABLE_POI 		= "POI";

	// Table FAVORITO
	private static final int CAMPO_ID_POI 		= 0; //ID_POI
	private static final int CAMPO_ID_PERFIL	= 1; //ID_PERFIL
	
	//Constructor
	public DbHandlerFavorito() {
		bd = DbHandler.getInstance();
	}
	
	public List<Favorito> cargarFavorito() throws SQLException {
		List<Favorito> list = new ArrayList<Favorito>();

		String selectQuery = "SELECT * FROM " + TABLE_FAVORITO;	
		Cursor cursor = bd.ejecutarConsulta(selectQuery); 

		if (cursor.moveToFirst()) {
			do {
				Favorito auxFavorito = new Favorito();
				auxFavorito.setIdPoi(Integer.parseInt(cursor.getString(CAMPO_ID_POI)));
				auxFavorito.setIdPerfil(Integer.parseInt(cursor.getString(CAMPO_ID_PERFIL)));
				list.add(auxFavorito);
			} while (cursor.moveToNext());
		}
		cursor.close();
		return list;
	}

	public void insertarFavorito(Favorito auxFavorito) throws SQLException {
		String insertRegister = "INSERT INTO " + TABLE_FAVORITO + " (ID_POI, ID_PERFIL) VALUES(" +
				Integer.toString(auxFavorito.getIdPoi()) + ", " + Integer.toString(auxFavorito.getIdPerfil()) + ")";

		bd.ejecutarInsert(insertRegister);
	}
	
	//return 0 - Si no existe el registro en la tabla FAVORITO
	public int existeFavorito(Favorito auxFavorito) throws SQLException {		
		int iCantReg = 0;

		String selectQuery = "SELECT COUNT(1) FROM " + TABLE_FAVORITO + " F, " + TABLE_POI + " P WHERE F.ID_POI = P.ID_POI AND P.ID_POI = " 
				+ Integer.toString(auxFavorito.getIdPoi());
		
		Cursor cursor = bd.ejecutarConsulta(selectQuery); 

		if (cursor.moveToFirst()) {
			do {
				iCantReg = Integer.parseInt(cursor.getString(0));
			} while (cursor.moveToNext());
		}
		
		cursor.close();

		if(iCantReg == 0)
			return 0;
		else
			return 1;			
	}
	
	public void eliminarFavorito(Favorito auxFavorito) throws SQLException {
		String deleteRegister = "DELETE FROM " + TABLE_FAVORITO + " WHERE ID_POI = " 
				+ Integer.toString(auxFavorito.getIdPoi());
		
		bd.ejecutarDelete(deleteRegister);
	}
}